import React, { useEffect, useState, Key } from 'react'
import { Card, Row, Col, Tree, Tag, Pagination, Table, Button, message } from "antd"
import { useNavigate, useParams } from 'react-router-dom'

import {
    getHospitalDepartmentRequest,
    getHosScheduleRuleRequest,
    getHosScheduleMessageRequest,
} from "@api/hospital/hospitalList"

import type {
    getHosDepartmentReturnType,
    bookingScheduleListType,
    getHosScheduleMessageReturnType,
} from "@api/hospital/model/hospitalListType"

export default function HospitalSchedule() {
    const { hoscode } = useParams()  //解构hoscode
    const navigate = useNavigate() //回到医院列表页面

    //页码
    const [current, setCurrent] = useState(1)
    const [pageSize, setPageSize] = useState(10)
    const [total, setTotal] = useState(0)

    //定义状态保存科室列表数据
    const [department, setDepartment] = useState<getHosDepartmentReturnType>([])
    //定义状态保存排班规则数据
    const [scheduleRule, setScheduleRule] = useState<bookingScheduleListType>([])
    //定义状态保存排班详细信息数据
    const [scheduleMessage, setScheduleMessage] = useState<getHosScheduleMessageReturnType>([])


    //定义状态保存depCode
    const [dpcode, setDpcode] = useState("")
    //定义状态保存workDate
    const [workDate, setWorkDate] = useState("")




    //1.请求医院科室列表的函数
    const getHosDepartment = async () => {
        const result = await getHospitalDepartmentRequest(hoscode as string)

        //把请求回来的科室列表数据保存在状态中
        setDepartment(result)

        //返回result 给第二个请求传递参数用
        return result

    }

    //2.请求排班规则的函数
    const getHosScheduleRule = async (initDepcode: string, current: number, pageSize: number) => {
        const result = await getHosScheduleRuleRequest({
            page: current,
            limit: pageSize,
            hoscode: hoscode as string,
            depcode: initDepcode
        })

        //把请求回来的排班规则数据保存在状态中
        setScheduleRule(result.bookingScheduleList)

        //把排班规则数据总数保存在状态
        setTotal(result.total)

        //返回result 给第三个请求传递参数用
        return result.bookingScheduleList

    }

    //3.请求排班日期详细数据
    const getHosScheduleMessage = async (depcode: string, workDate: string) => {
        const result = await getHosScheduleMessageRequest({
            hoscode: hoscode as string,
            depcode: depcode,
            workDate: workDate,
        })

        //把请求回来的排班规则数据保存在状态中
        setScheduleMessage(result)
    }



    //初始化的时候按顺序依次发送3个请求
    useEffect(() => {
        const rquest = async () => {
            //1.请求所有科室数据
            const department = await getHosDepartment();
            //2.根据科室数据获取初始的科室信息
            const initDepcode = (department[0].children as getHosDepartmentReturnType)[0].depcode

            //3.把初始的科室信息传递给 请求排班列表函数 得到排班列表数据
            const scheduleRule = await getHosScheduleRule(initDepcode, current, pageSize)

            //把depCode保存在状态
            setDpcode(initDepcode)

            //4.根据排班列表数据获取初始的日期信息
            const initWorkDate = scheduleRule[0].workDate

            //把workDate保存在状态
            setWorkDate(initWorkDate)

            //5.把初始日期信息传递给 请求排班日期信息函数 得到详细日期数据
            await getHosScheduleMessage(initDepcode, initWorkDate);
        }
        rquest()
    }, [])



    //列的配置
    const columns = [
        {
            title: "序号",
            render: (_a: any, _b: any, index: number) => {
                return index + 1;
            },
        },
        {
            title: "职称",
            dataIndex: "title",
        },
        {
            title: "号源时间",
            dataIndex: "createTime"
        },

        {
            title: "可预约数",
            dataIndex: "amount",
        },
        {
            title: "剩余预约数",
            dataIndex: "availableNumber",
        },
        {
            title: "挂号费(元)",
            dataIndex: "hosScheduleId",
        },
        {
            title: "擅长技能",
            dataIndex: "skill",
        },
    ];


    //1.切换页码的函数
    const changePageHandle = async (current: number, pageSize: number) => {
        setCurrent(current)
        setPageSize(pageSize)
        //发送请求
        const result = await getHosScheduleRule(dpcode, current, pageSize)

        //根据科室排班请求数据的第一个 请求详细信息
        const firstWorkDate = result[0].workDate;

        setWorkDate(firstWorkDate)
        //根据第一个科室排班的信息 获取表格详细信息
        getHosScheduleMessage(dpcode , firstWorkDate);
    }


    //2.点击tree的回调函数
    const changeTreeHandle = async (depcode: Key[]) => {
        //如果再次点击 点击的是取消 不执行操作
        if (depcode.length === 0) {
            return
        }

        //拿到当前点击的depcode
        const newDepCode = depcode[0] as string
        //把拿到的depcode设置到状态中
        setDpcode(newDepCode)

        try {
            //根据点击拿到depcode 发送获取排班规则请求
            const result = await getHosScheduleRule(newDepCode, current, pageSize)
            //根据排班规则请求的返回值拿到第一个数据的 workDate
            const newWorkDate = result[0].workDate
            setWorkDate(newWorkDate)
            await getHosScheduleMessage(newDepCode, newWorkDate)
        } catch (e) {
            //如果点击的不是第一个科室就返回没有数据 并清空表格
            message.error("没有数据");
            setScheduleMessage([]);
        }

    }


    //3.点击Tage的回调函数
    const changeTagHandle = (workDate: string) => {
        return async () => {
            //把当前点击的Tag的workDate保存到状态
            setWorkDate(workDate)
            await getHosScheduleMessage(dpcode, workDate)
        }
    }



    //4.显示total函数
    const showTotalHandle = (total: number) => {
        return <span>{`数据总共有${total}条`}</span>
    }


    return (
        <div>
            <Card>
                <p>选择：北京协和医院 / 多发性硬化专科门诊 / 2022-04-28</p>
                <Row gutter={20}>

                    <Col span={5}>
                        <div style={{ height: 400, border: "1px solid silver", overflow: "auto" }}>
                            <Tree
                                treeData={department as []}  //数据添加到树中
                                fieldNames={{ title: "depname", key: "depcode" }} //关联数据
                                expandedKeys={["a4e171f4cf9b6816acdfb9ae62c414d7"]}  //展开节点
                                onSelect={changeTreeHandle}  //点击节点的函数
                            />
                        </div>
                    </Col>

                    <Col span={19}>
                        <div style={{ marginBottom: 20, cursor: "pointer" }}>
                            {
                                scheduleRule.map((item) => {
                                    return (
                                        <Tag
                                            key={item.workDate}
                                            style={{
                                                marginBottom: 1,
                                                background: item.workDate === workDate ? "#1DA57A" : ''
                                            }}
                                            onClick={changeTagHandle(item.workDate)}
                                        >
                                            <div>{item.workDate} {item.dayOfWeek}</div>
                                            <div>{item.availableNumber} / {item.reservedNumber}</div>
                                        </Tag>
                                    )
                                })
                            }
                        </div>

                        <Pagination
                            showSizeChanger
                            current={current}
                            pageSize={pageSize}
                            total={total}
                            pageSizeOptions={[1, 5, 10, 15, 20, 30, 40]}
                            onChange={changePageHandle} //改变页码函数
                            showTotal={showTotalHandle}
                        />

                        <Table
                            style={{ marginTop: 20 }}
                            columns={columns}
                            dataSource={scheduleMessage}
                            bordered
                            rowKey="id"
                            pagination={false}
                        />

                        <Button style={{ marginTop: 20 }} onClick={() => navigate(-1)}>返回</Button>
                    </Col>
                </Row>
            </Card>
        </div>
    )
}
